/*
//  Copyright © 2014 Allen County Public Library.

  //        ACPL Mobile is free software: This program is distributed and you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.  ACPL Mobile is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY, including without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with ACPL Mobile. If not, see http://www.gnu.org/licenses/.
 * Author: James Harpe
 * 
 * Description: This service handles event notifications. 
 * 
 */

package us.in.lib.acpl.Mobile_ACPL.service.event;


import android.R;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.BitmapFactory;
import android.support.v4.app.NotificationCompat;
import android.util.Xml;

import java.io.IOException;
import java.io.StringReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.StringTokenizer;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import us.in.lib.acpl.Mobile_ACPL.EventDetailActivity;
import us.in.lib.acpl.Mobile_ACPL.event.Event;
import us.in.lib.acpl.Mobile_ACPL.service.WakefulIntentService;
import us.in.lib.acpl.Mobile_ACPL.util.JSONArrayPrefs;
import us.in.lib.acpl.Mobile_ACPL.util.RestClient;
import us.in.lib.acpl.Mobile_ACPL.util.RestClient.RequestMethod;
import us.in.lib.acpl.Mobile_ACPL.ws.EventHandler;

public class EventNotifyService extends WakefulIntentService {

	private final double MILLISECONDS_PER_HOUR = 3600000.0;
	private ArrayList<Event> event;
	private SharedPreferences prefs;

	public EventNotifyService() {
		super("NotifyService");
	}

	@Override
	public void doWakefulWork(Intent intent) {
		System.out.print("starting service");
		prefs = this.getSharedPreferences("myPrefs",
				Context.MODE_WORLD_WRITEABLE);

		
		String user = prefs.getString("user", null);
		ArrayList<String> toNotify = JSONArrayPrefs.getStringArrayPref(
				getApplicationContext(), "events");
		String hoursInAdvance = prefs.getString("hoursAhead", "3");
		if(toNotify==null||toNotify.size()==0){
			return;
		}
		ArrayList<Event> events = getEvents();

		for (Event ev : events) {

			String id = ev.getId();
			if (toNotify.contains(id)) {

				String date = ev.getDate();
				String time = ev.getTime();
				if (time.indexOf(":") == 1) {
					time = "0" + time;
				}
				String dateTime = date + " " + time;
				Date eventDate = null;
				Date currDate = new Date();
				SimpleDateFormat parser = new SimpleDateFormat(
						"yyyy/MM/dd h:mm a");
				try {
					eventDate = parser.parse(dateTime);
				} catch (ParseException e) {
					e.printStackTrace();
					time = "00:00 AM";
					dateTime = date + " " + time;
					try {
						eventDate = parser.parse(dateTime);
					} catch (ParseException e1) {
						e1.printStackTrace();
					}
				}

				double diff = (eventDate.getTime() - currDate.getTime())
						/ MILLISECONDS_PER_HOUR;
				if (diff <= Integer.parseInt(hoursInAdvance)) {
					notifyEvent(ev);
					toNotify.remove(id);
					JSONArrayPrefs.setStringArrayPref(getApplicationContext(),
							"events", toNotify);
				}

			}

		}

	}

	public void notifyEvent(Event event) {

		NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
		int icon = R.drawable.ic_dialog_info;

		long when = System.currentTimeMillis();

		Intent intent = new Intent(this, EventDetailActivity.class);
		intent.putExtra("title", event.getTitle());
		intent.putExtra("date", event.getStringDate());
		intent.putExtra("time", event.getTime());
		intent.putExtra("id", event.getId());
		intent.putExtra("library", event.getLibrary());
		intent.putExtra("location", event.getLocation());
		intent.putExtra("length", event.getLength());
		intent.putExtra("description", event.getDescription());
		intent.putExtra("ageGroups", event.getAgeGroups());
		intent.putExtra("eventTypes", event.getEventTypes());
		intent.putExtra("otherInfo", event.getOtherInfo());

		PendingIntent contentIntent = PendingIntent.getActivity(this,
				Integer.parseInt(event.getId()), intent, 0);
		Notification noti = new NotificationCompat.Builder(this)
				.setWhen(when)
				.setContentTitle("Upcoming event")
				.setContentText(
						event.getTitle() + " starts soon. Touch for details")
				.setTicker("Upcoming Event").setAutoCancel(true)
				.setSmallIcon(icon)
				.setContentIntent(contentIntent)
				.getNotification();

		mNotificationManager.notify(Integer.parseInt(event.getId()), noti);
	}

	private ArrayList<Event> getEvents() {
		RestClient client = new RestClient(EventHandler.EVENT_URL);

		client.AddParam("lib", "all");
		client.AddParam("nd", "3");
		client.AddParam("dm", "exml");

		try {
			client.Execute(RequestMethod.GET);
		} catch (Exception e) {
			e.printStackTrace();
		}

		String response = client.getResponse();
		ArrayList<Event> list = new ArrayList<Event>();

		if (response == null) {
			return list;
		}
		Event event = new Event();
		XmlPullParser parser = Xml.newPullParser();

		try {
			parser.setInput(new StringReader(response));

			int eventType = parser.next();

			while (eventType != XmlPullParser.END_DOCUMENT) {
				if (eventType == XmlPullParser.END_TAG) {
					String name = parser.getName();
					if (name.equalsIgnoreCase("item")) {
						list.add(event);
						event = new Event();
					}
				}

				if (eventType == XmlPullParser.START_TAG) {
					String name = parser.getName();
					if (name.equalsIgnoreCase("title")) {
						String text = parser.nextText();
						if (text.equalsIgnoreCase("No Events Currently Scheduled")) {
							break;
						}
						event.setTitle(text);
					}
					if (name.equalsIgnoreCase("date1")) {
						event.setDate(parser.nextText());
					}
					if (name.equalsIgnoreCase("date")) {
						event.setStringDate(parser.nextText());
					}
					if (name.equalsIgnoreCase("time")) {
						event.setTime(parser.nextText());
					}
					if (name.equalsIgnoreCase("length")) {
						event.setLength(parser.nextText());
					}
					if (name.equalsIgnoreCase("description")) {
						event.setDescription(parser.nextText());
					}
					if (name.equalsIgnoreCase("location")) {
						event.setLocation(parser.nextText());
					}
					if (name.equalsIgnoreCase("library")) {
						event.setLibrary(parser.nextText());
					}
					if (name.equalsIgnoreCase("id")) {
						event.setId(parser.nextText());
					}
					if (name.equalsIgnoreCase("eventtypes")) {
						ArrayList<String> types = new ArrayList<String>();
						StringTokenizer tokens = new StringTokenizer(
								parser.nextText(), ",");
						while (tokens.hasMoreTokens()) {
							String item = tokens.nextToken();
							if (item != null && (!item.equalsIgnoreCase(""))
									&& (!item.equalsIgnoreCase(" "))) {
								types.add(item);
							}
						}
						event.setEventTypes(types.toArray(new String[0]));
					}
					if (name.equalsIgnoreCase("agegroups")) {
						ArrayList<String> types = new ArrayList<String>();
						StringTokenizer tokens = new StringTokenizer(
								parser.nextText(), ",");
						while (tokens.hasMoreTokens()) {
							String item = tokens.nextToken();
							if (item != null && (!item.equalsIgnoreCase(""))
									&& (!item.equalsIgnoreCase(" "))) {
								types.add(item);
							}
						}

						event.setAgeGroups(types.toArray(new String[0]));
					}

					if (name.equalsIgnoreCase("signup")) {
						event.setSignup(parser.nextText());
					}
					if (name.equalsIgnoreCase("otherinfo")) {
						event.setOtherInfo(parser.nextText());
					}
				}
				eventType = parser.next();
			}
		} catch (XmlPullParserException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return list;
	}

}